package cn.bonoon.kernel.web.controllers;

import javax.servlet.http.HttpServletRequest;

import org.batatasframework.web.RequestParameterReader;

import cn.bonoon.kernel.events.PanelEvent;
import cn.bonoon.kernel.menus.ChannelDefinition;
import cn.bonoon.kernel.menus.MenuableDefinition;
import cn.bonoon.kernel.menus.ModuleDefinition;
import cn.bonoon.kernel.menus.ModuleManager;
import cn.bonoon.kernel.menus.privileges.PrivilegeInspector;
import cn.bonoon.kernel.security.LogonUser;
import cn.bonoon.kernel.support.IOperator;
import cn.bonoon.kernel.support.services.UserService;
import cn.bonoon.kernel.web.models.LayoutModel;

public class StandardLayoutParser extends StandardPanelParser {
	
	public StandardLayoutParser(ModuleManager moduleManager, UserService userService) {
		super(moduleManager, userService.policy());
	}
	
	@Override
	public PanelEvent parse(String mid, HttpServletRequest request, LogonUser user) throws Exception {
		
		LayoutModel model = new LayoutModel(mid, request, moduleManager);
		MenuableDefinition item = moduleManager.find(model);
		PanelEvent event = accessCheck(model, item, user);
		PrivilegeInspector privilege = event.getPrivilege();
		ModuleDefinition module = item.getModule();
		ChannelDefinition channel = item.getChannel();
		
		model.initLayout(item.navigation(), module.getStyle(), item.getDescribe());
		RequestParameterReader reader = RequestParameterReader.valueOf(request);
		//频道就不允许另外重新生成，必须是定义文件里定义的
		model.buildChannel(module, user, reader, privilege, channel.getId());
		
		//这里可以使用外部的或自定义的菜单来实现
		buildMenu(user, reader, model, channel, privilege, item.getId());
		return event;
	}

	//生成菜单，如果需要使用自定义的菜单，子类可以重写这个方法来实现
	protected void buildMenu(IOperator user, RequestParameterReader reader, 
			LayoutModel model, ChannelDefinition channel, 
			PrivilegeInspector privilege, String selected) throws Exception{
		model.buildMenu(user, reader, channel, privilege, selected);
	}
}
